<template>
  <div class="updatePasswordPage">
    <a-card title="修改密码" style="width: 100%; margin-bottom: 20px;">
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item label="当前密码">
          <a-input-password v-model:value="passwordForm.currentPassword" placeholder="请输入当前密码" />
        </a-form-item>
        <a-form-item label="新密码">
          <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认新密码">
          <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </a-form-item>
      </a-form>
      <div style="text-align: right; margin-top: 20px;">
        <a-button type="primary" @click="submitForm">保存</a-button>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { updatePasswordUsingPost, updateUserUsingPost } from '@/api/userController';
import { useRouter } from 'vue-router';

interface PasswordForm {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const passwordForm = ref<PasswordForm>({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
});
const router = useRouter();

async function submitForm() {
  // 简单的表单验证
  if (!passwordForm.value.currentPassword) {
    message.error('请输入当前密码');
    return;
  }
  if (!passwordForm.value.newPassword) {
    message.error('请输入新密码');
    return;
  }
  if (!passwordForm.value.confirmPassword) {
    message.error('请再次输入新密码');
    return;
  }

  // 增加新的校验逻辑
  if (passwordForm.value.newPassword === passwordForm.value.currentPassword) {
    message.error('新密码不能与当前密码相同');
    return;
  }
  if (passwordForm.value.newPassword.length <= 6) {
    message.error('新密码长度必须大于6位');
    return;
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    message.error('两次输入的新密码不一致');
    return;
  }

  try {
    const response = await updatePasswordUsingPost({
      userPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword,
    });
    console.log("userPassword" + passwordForm.value.currentPassword);
    console.log("newPassword" + passwordForm.value.newPassword);
    if (response.data.data) {
      message.success("密码修改成功");
      // 清空表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      };
      router.push('/');
    } else {
      console.error('修改失败', response.data.message);
      message.error('修改失败: ' + response.data.message);
    }
  } catch (error) {
    console.error('保存错误', error);
    message.error('保存错误');
  }
}
</script>

<style scoped>
.updatePasswordPage {
  max-width: 700px;
  margin: 0 auto;
}

.updatePasswordPage .ant-input-password {
  width: 100%;
}
</style>
